const router = require('koa-router')();
const userModel = require('../models/user')
const allowhostModel = require('../models/allowhost')
const tokenHelper =  require('../util/token-helper')
const ApiError = require('../error/api_error');
const ApiErrorNames = require('../error/api_error_name');
const jwt = require('jsonwebtoken')
const config = require('../config')


//用户登录
router.post('/', async (ctx)=>{
  //判断客户端IP是否是管理主机
 let pass = false
  await allowhostModel.findOne({host:'0.0.0.0'}).exec().then(res=>{
    if(res) pass = true
  })
  if(!pass){
   await allowhostModel.findOne({host:ctx.request.ip}).exec().then(res=>{
     //如果有记录或是从服务器本机登录放行
    if(res || ctx.request.ip == ctx.request.host ){
      pass = true
    }
  })
  }
  if(!pass) return
  const data = ctx.request.body;

  // console.log(data)
  //  let query =await new Promise((resolve,reject)=>{
  //   userModel.find({usernmae:data.username},(err,res)=>{
  //     if (err){reject(err)}
  //     if(res){resolve(res)}
  //   });
  // });

  // await userModel.findOne({username:data.username,password:data.password},(err,docs)=>{
  //   //当没有错误并且有返回值
  //   if(!err && docs){
  //      console.log('db is OK!  ')
  //     let user = {userId:docs._id,userName:data.username};
  //     let token = tokenHelper.createToken(user)
  //     ctx.body = {userId:docs._id,userName:docs.username,token:token};
  //   }else{
  //     // ctx.body = '用户名或密码错误'
  //      ctx.status = 250;
  //     // console.log(ctx)
  //     // throw new ApiError(ApiErrorNames.USER_ERROR);
  //   }
  // });
await userModel.findOne({username:data.username,password:data.password}).exec().then(res=>{
  if(res){
    let user = {userId: res._id, userName: data.username,rank:res.rank};
    let token = tokenHelper.createToken(user)
    ctx.body = {userId: res._id, userName: res.username, token: token,rank:res.rank};
  }else {
       ctx.status = 250;//用户名或密码错误
  }
})
  // console.log(query);
  //  if(query){
  //    ctx.body = query
  //  }
  // async (data)=>{
  //    await ((data)=>{ Model.findById(id).exec()}).then()
  // }
})

//检查token是否合法
router.post('/check',async (ctx)=>{
  const data = ctx.request.body;
  try {
    await jwt.verify(data.token,config.tokenSecret);
     ctx.body = {code:0,msg:'ok'};
    }catch (error) {
    ctx.body = {code:1,msg:'token失效或过期'};
  }
})


module.exports = router;
